package com.teradata.fbj.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.teradata.fbj.pojo.linkParams;
import com.teradata.fbj.util.GetConnection;
import com.teradata.fbj.util.freeJDBC;
@Repository
public class ConnDataBaseDaoImpl implements IConnDataBaseDao{
	
	@Autowired
	private GetConnection getcon = new GetConnection();
	private freeJDBC freeJ = new freeJDBC();
	private Connection connection = null;
	private PreparedStatement ps = null;
	private ResultSet rs = null;
	
	
	
	public List<String> getTableName(linkParams lp) throws Exception{
		List<String> tableList = new ArrayList<String>();
		try {
			connection = getcon.getConnection(lp);
			if(connection ==null){
				System.out.println("连接失败！");
			}
			String jdbcUrl = lp.getBaseUrl();
			String database = "'" + jdbcUrl.substring(28) + "'";
			String sql = "SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = "+database;
			ps= connection.prepareStatement(sql);
			rs = ps.executeQuery();
			ResultSetMetaData rsmd = ps.getMetaData();
			int columnCount = rsmd.getColumnCount();
			while(rs.next()){
				for(int i = 1;i<=columnCount;i++){
					tableList.add(rs.getString(i));
				}
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}finally {
			freeJ.free(rs, ps, connection);
		}
		return tableList;
	}


	public int createModel(String tableSql, linkParams lp) throws Exception {
		int result =1 ;
		try {
			connection = getcon.getConnection(lp);
			if(connection ==null){
				System.out.println("连接失败！");
			}
			String sql =tableSql;
			ps= connection.prepareStatement(sql);
			result = ps.executeUpdate();
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			freeJ.free(rs, ps, connection);
		}
		return result;
	}

}
